package de.tabuma.ssoclient.logik;

import java.util.*;
import de.tabuma.ssoclient.entity.UserGroup;

/**
 *
 * @author alefen
 */
public class UserGroupHashFacade {
    private static Hashtable<String,List<UserGroup>> hash = new Hashtable<String, List<UserGroup>>();
    public synchronized static void put(UserGroup UserGroup, String ssoId) {
        List<UserGroup> pList = hash.get(ssoId+"_group"+UserGroup.getGroupId());
        if(pList==null) {
            pList = new ArrayList<UserGroup>();
        }
        for(int i=0;i<pList.size();i++) {
            UserGroup p = pList.get(i);
            if(p.getId().intValue()==UserGroup.getId().intValue()) {
                pList.set(i, UserGroup);
                hash.put(ssoId, pList);
                return;
            }
        }

        pList.add(UserGroup);
        hash.put(ssoId+"_group"+UserGroup.getGroupId(), pList);
    }

    public synchronized static UserGroup get(int id, String ssoId) {
        Enumeration<String> enu = hash.keys();
        while(enu.hasMoreElements()) {
            String key = enu.nextElement();
            if(key.indexOf(ssoId)!=-1) {
                List<UserGroup> pList = hash.get(key);
                for(int i=0;i<pList.size();i++) {
                    UserGroup p = pList.get(i);
                    if(p.getId().intValue()==id) {
                        return p;
                    }
                }
            }
        }
        return null;
    }

    public synchronized static void remove(int id, String ssoId) {
        Enumeration<String> enu = hash.keys();
        while(enu.hasMoreElements()) {
            String key = enu.nextElement();
            if(key.indexOf(ssoId)!=-1) {
                List<UserGroup> pList = hash.get(key);
                for(int i=0;i<pList.size();i++) {
                    UserGroup p = pList.get(i);
                    if(p.getId().intValue()==id) {
                        pList.remove(i);
                        hash.put(key, pList);
                        return;
                    }
                }
            }
        }
    }

    public synchronized static List<UserGroup> getList(int groupId, String ssoId) {
        return hash.get(ssoId+"_group"+groupId);
    }

    public synchronized static void setList(List<UserGroup> pList,int groupId, String ssoId) {
        hash.put(ssoId+"_group"+groupId, pList);
    }
}
